﻿using System.Windows.Forms;
using Deferred.Library.Configuration;

namespace Deferred.Editor.Gui
{
    public partial class CommandLinePanel : UserControl
    {
        ICommandLineEngine commandLine;
        int commandHistoryIndex = -1;

        public CommandLinePanel(ICommandLineEngine commandLine)
        {
            this.commandLine = commandLine;
            foreach (string line in commandLine.Output)
            {
                AppendOutputLine(line);
            }
            commandLine.OutputChanged += new OutputUpdateEvent(AppendOutputLine);
            InitializeComponent();
        }

        private void currentEntryTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (Keys.Return == e.KeyCode)
            {
                AppendOutputLine("");
                commandLine.ProcessInput(currentEntryTextBox.Text);
                AppendOutputLine(currentEntryTextBox.Text);
                currentEntryTextBox.Clear();
                e.Handled = true;
                commandHistoryIndex = -1;
            }
            else if (Keys.Up == e.KeyCode)
            {
                if (commandHistoryIndex < commandLine.CommandHistory.Count - 1)
                {
                    commandHistoryIndex++;
                    currentEntryTextBox.Text = commandLine.CommandHistory[commandHistoryIndex];
                }
            }
            else if (Keys.Down == e.KeyCode)
            {
                if (commandHistoryIndex > -1)
                {
                    commandHistoryIndex--;
                    if (-1 == commandHistoryIndex)
                    {
                        currentEntryTextBox.Text = "";
                    }
                    else
                    {
                        currentEntryTextBox.Text = commandLine.CommandHistory[commandHistoryIndex];
                    }
                }
            }
        }

        private void AppendOutputLine(string newLine)
        {
            outputTextBox.Text = newLine + "\r\n" + outputTextBox.Text;
        }
    }
}
